package com.bajiao.admin.controller.common;

import com.aliyun.oss.OSSClient;
import com.bajiao.common.api.vo.Result;
import com.bajiao.common.constant.CommonConstant;
import com.bajiao.service.config.ConfigService;
import com.bajiao.third.utils.OSSClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @Author FanJq
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {

    @Resource
    private ConfigService configService;


    @GetMapping("/403")
    public Result<?> noAuth() {
        return Result.error("没有权限，请联系管理员授权");
    }

    @PostMapping(value = "/uploadAli")
    public Result<?> uploadAli(HttpServletRequest request, HttpServletResponse response) {
        Result<?> result = new Result<>();
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            // 获取上传文件对象
            MultipartFile mf = multipartRequest.getFile("file");
            // 获取文件名
            String fileName = mf.getOriginalFilename().trim();
            if (StringUtils.isEmpty(mf.getOriginalFilename())) {
                result.setSuccess(false);
                result.setMessage("no file");
                return result;
            }
            String bucketName = "";
            String resultUrl = "";
            //判断配置参数是否正常获取
            Map map = configService.queryNameAndValueByGroup(CommonConstant.OSS_CONFIG_GROUP);
            if (map.size() == 5) {
                bucketName = (String) map.get("bucketName");
                resultUrl = (String) map.get("resultUrl");
            }
            boolean ok = OSSClientUtils.checkExist(bucketName, fileName);
            String url = "";
            if (ok) {
                url = resultUrl + fileName;
            } else {
                url = OSSClientUtils.uploadFile(mf.getInputStream(), fileName);
            }
            result.setMessage(url);
            result.setSuccess(true);
        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * @param modelAndView
     * @return
     * @功能：pdf预览Iframe
     */
    @RequestMapping("/pdf/pdfPreviewIframe")
    public ModelAndView pdfPreviewIframe(ModelAndView modelAndView) {
        modelAndView.setViewName("pdfPreviewIframe");
        return modelAndView;
    }


    /**
     * 获取后台动态配置数据
     *
     * @return
     */
    @RequestMapping("/config")
    public Result getConfig() {
        Map<String, Object> result = new HashMap<>();
        //判断配置参数是否正常获取
        Map map = configService.queryNameAndValueByGroup(CommonConstant.OSS_CONFIG_GROUP);
        map.remove("accessKeyId");
        map.remove("accessKeySecret");
        result.putAll(map);
        return Result.ok(map);
    }

    /**
     * 把指定URL后的字符串全部截断当成参数
     * 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     *
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

}
